import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import store from "../store"
import { toast } from "../utils/toast"

Vue.use(VueRouter)

// 解决路由多点得报错
import Router from 'vue-router';
const originalPush = Router.prototype.push

Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home
  },
  {
    path: '/allgoods',
    name: 'AllGoods',
    component: () => import(/* webpackChunkName: "allgoods" */ '../views/AllGoods.vue')
  },
  // {
  //   path: '/frees',
  //   name: 'Frees',
  //   component: () => import(/* webpackChunkName: "frees" */ '../views/Frees.vue')
  // },
  {
    path: '/myorders',
    name: 'MyOrders',
    component: () => import(/* webpackChunkName: "myorders" */ '../views/MyOrders.vue')
  },
  {
    path: '/personal',
    name: 'Personal',
    component: () => import(/* webpackChunkName: "personal" */ '../views/Personal.vue'),
    redirect: '/personal/cart',
    children: [
      {
        path: 'cart',
        name: 'Cart',
        component: () => import(/* webpackChunkName: "cart" */ '../components/personal/Cart.vue'),
      },
      {
        path: 'user',
        name: 'User',
        component: () => import(/* webpackChunkName: "user" */ '../components/personal/User.vue')
      }
    ]
  }
  ,
  {
    path: '/goodsdetail',
    name: 'GoodsDetail',
    component: () => import(/* webpackChunkName: "goodsdetail" */ '../views/GoodsDetail.vue')
  },
  {
    path:'*',
    component:()=>import(/* webpackChunkName: "goodsdetail" */ '../components/common/404.vue')
  }
]

const router = new VueRouter({
  // mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  const regPersonal = /\/personal/;
  const regMyOrders = /\/myorders/;
  const token = localStorage.getItem('x-auth-token');
  if (regPersonal.test(to.path) || regMyOrders.test(to.path)) {

    if (!token) {
      store.state.isShowLogin = true
      return toast("请先登录", "warning");
    }else{
      next()
    }
  }
  next()
})

export default router
